package blog.controller.admin;


import blog.entity.Comment;
import blog.service.CommentService;
import blog.util.Result;
import blog.util.ResultGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author StarryX
 * @since 2020-10-01
 */
@Controller
@RequestMapping("/admin")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @GetMapping("/comments/list")
    @ResponseBody
    public Result list(@RequestParam Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        Page<Comment> page = new Page<>(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("limit").toString()));
        if (params.get("page").toString().equals("asc")){       //查询出的分页按升序排序
            commentService.page(page, new QueryWrapper<Comment>()
                    .orderByAsc(StringUtils.isEmpty(params.get("sidx")) ? "update_time" : params.get("sidx").toString()));     //todo： 记得修改前端页面js中的 index 属性，将改为与数据库表中字段一致
        }else{                                                  //查询出的分页按降序排序
            commentService.page(page, new QueryWrapper<Comment>()
                    .orderByDesc(StringUtils.isEmpty(params.get("sidx")) ? "update_time" : params.get("sidx").toString()));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", page.getRecords());
        resultMap.put("currPage", page.getCurrent());
        resultMap.put("totalPage", page.getPages());
        resultMap.put("totalCount", page.getTotal());
        return ResultGenerator.genSuccessResult(resultMap);
    }

    @GetMapping("/comments")
    public String list(HttpServletRequest request) {
        request.setAttribute("path", "comments");
        return "admin/comment";
    }

    //todo: 此处删除了 审查 模块，记得在前端页面删除对应的代码

    //todo: 此处删除了 回复 模块，记得在前端页面删除对应的代码

    @PostMapping("/comments/delete")
    @ResponseBody
    public Result delete(@RequestBody Integer[] ids) {
        if (ids.length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        if (commentService.removeByIds(Arrays.asList(ids))) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("刪除失败");
        }
    }
}

